package kr.or.kead.module;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.regex.Pattern;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class RoomCheck extends JPanel implements ActionListener {
	private JRadioButton radioBtn1;
	private JRadioButton radioBtn2;
	private JTextField txtRoomNum;

	public RoomCheck() {
		init();
	}

	private void init() {
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		
		radioBtn1 = new JRadioButton("통학", true);
		radioBtn1.addActionListener(this);
		add(radioBtn1);
		
		radioBtn2 = new JRadioButton("기숙사");
		radioBtn2.addActionListener(this);
		add(radioBtn2);
		
		ButtonGroup bg = new ButtonGroup();
		
		bg.add(radioBtn1);
		bg.add(radioBtn2);
		
		txtRoomNum = new JTextField();
		txtRoomNum.addKeyListener(new txtRoomNumKeyListener());		
		add(txtRoomNum);
		txtRoomNum.setColumns(10);
		txtRoomNum.setEditable(false);
		
	}


	public String getTxtRoomNum() {
		return txtRoomNum.getText();
	}



	public void setTxtRoomNum(String txtRoomNum) {
		this.txtRoomNum.setText(txtRoomNum);
	}



	public boolean getRadioBtn1() {
		return radioBtn1.isSelected();
	}



	public void setRadioBtn1(boolean compare) {
		radioBtn1.setSelected(compare);
	}



	public boolean getRadioBtn2() {
		return radioBtn2.isSelected();
	}



	public void setRadioBtn2(boolean compare) {
		radioBtn2.setSelected(compare);
	}



	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == radioBtn1) {
			radioBtn1ActionPerformed(e);
		}else if (e.getSource() == radioBtn2) {
			radioBtn2ActionPerformed(e);
		}
	}

	protected void radioBtn1ActionPerformed(ActionEvent e) {
		txtRoomNum.setText("");		
		txtRoomNum.setEditable(false);		
	}
	
	private void radioBtn2ActionPerformed(ActionEvent e) {	
		txtRoomNum.setEditable(true);
		txtRoomNum.setFocusable(true);
	}
	
	private class txtRoomNumKeyListener extends KeyAdapter {
		public void keyReleased(KeyEvent e) {
			if(Pattern.matches("^[1-5]{1}$", String.valueOf(e.getKeyChar())) == false&&
					e.getKeyChar() != KeyEvent.VK_ENTER) {
				JOptionPane.showMessageDialog(null, "숫자만 입력");
				txtRoomNum.setText((String) txtRoomNum.getText().subSequence(0, txtRoomNum.getText().length()-1));
			}else {
				if(txtRoomNum.getText().length() >= 3) {
					txtRoomNum.setFocusable(false);					
				}
			}
		}		
	}	
}
